package org.ykhl.log.commons.receiver;

import org.ykhl.mq.commons.ConnectionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by zkf on 2015/12/10.
 */
public abstract class LogReceiver {
    private static final Logger LOG = LoggerFactory.getLogger(LogReceiver.class);
    protected LogListener listener;
    private boolean running = false;
    protected String mqNameServerAddress;
    protected Boolean useSsl;

    public void setMqNameServerAddress(String mqNameServerAddress) {
        this.mqNameServerAddress = mqNameServerAddress;
    }

    public void setUseSsl(boolean useSsl) {
        this.useSsl = useSsl;
    }

    public LogListener getListener() {
        return listener;
    }

    public void setListener(LogListener listener) {
        this.listener = listener;
    }

    public boolean isRunning(){
        return running;
    }

    /**
     * 用于启动消息接收器的方法，调用前请确保listener已经设置。
     *
     * @throws ConnectionException
     */
    public void start() throws ConnectionException{
        if(running)		// already running
            return;
        if(listener == null)	// listener not set, can't consume messages for now
            throw new NullPointerException("listener not set.");
        if(mqNameServerAddress == null || "".equals(mqNameServerAddress))
            throw new NullPointerException("mqNameServerAddress not set.");

        try{
            doStart();

            running = true;
        } catch(Exception e){
            throw new ConnectionException(e);
        }
    }

    /**
     * 用于停止消息接收器的方法。
     *
     * @throws ConnectionException
     */
    public void stop() throws ConnectionException{
        if(!running)
            return;

        try{
            doStop();

            running = false;
        } catch(Exception e){
            throw new ConnectionException(e);
        }
    }

    protected abstract void doStart() throws Exception;
    protected abstract void doStop() throws Exception;
}
